<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import { ref, watchEffect, onMounted, onUnmounted, reactive } from 'vue'

import { getColWidth, setLastWidth } from '@/template/page/common/FormatData'
import { isDate, formatDate } from '@/utils/formatDate'

import eventBus from '@/libs/eventBus'

const props = defineProps({
  partParams: {
    type: Object
  },
  tabInfo: {
    type: Object
  }
})
const loading = ref(false) // 列表的加载中

const headList = ref([])
const emit = defineEmits(['selection-change'])
/** 多选操作 */
const handleSelectionChange = (val: any) => {
  val.length && emit('selection-change', val, headList.value)
}

// 创建 ref 来引用容器元素
const boxRef = ref()
// 标记容器宽度是否发生变化
const isWidthChanged = ref(false)

const getBoxWidth = () => {
  return boxRef.value?.offsetWidth
}

// 创建 ResizeObserver 实例
let resizeObserver: any
onMounted(() => {
  // 创建 ResizeObserver 实例，传入回调函数
  resizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      // 这里可以编写具体要执行的操作，例如更新状态、发送请求等
      // 这里简单地将 isWidthChanged 设置为 true 表示宽度已变化
      isWidthChanged.value = true
      console.log('容器宽度变化为:', entry.contentRect.width)
      if (entry.contentRect.width) {
        // 可以在这里添加更多操作，比如调用某个函数
        performSpecificOperation(entry.contentRect.width)
      }
    }
  })

  // 开始监听容器元素的尺寸变化
  if (boxRef.value) {
    resizeObserver.observe(boxRef.value)
  }
})

onUnmounted(() => {
  // 当组件卸载时，停止监听并清理资源
  if (resizeObserver && boxRef.value) {
    resizeObserver.unobserve(boxRef.value)
  }
})

// 定义一个具体的操作函数
const performSpecificOperation = (newWidth: any) => {
  console.log('执行了特定操作，新宽度为:', newWidth)
  render(newWidth)
  // 这里可以添加更多复杂的操作，如更新数据、调用 API 等
}

const formInline = reactive({
  FSeq: '',
  FNumber: '',
  FName: '',
  FInspectResult: ''
})

const pageInfo = ref()
//检验结果
const resultCol = ref<any[]>([])
const resultList = ref<any[]>([])
//整体抽样
const sampleCol = ref<any[]>([])
const sampleList = ref<any[]>([])
//缺陷记录
const bugCol = ref<any[]>([])
const bugList = ref<any[]>([])
//检验项目
const inspectCol = ref<any[]>([])
const inspectList = ref<any[]>([])

const render = (contentWidth?: number) => {
  let resultWidth = contentWidth ? contentWidth : getBoxWidth()
  //渲染列表
  if (resultCol.value.length) {
  //去掉删除按钮的宽度
  const width = resultWidth - 80
    //当宽度之和等于百分比的时候 最后一列需要处理 解决小空隙问题
    const sumPercent = resultCol.value.reduce((first: any, cur: any) => first + cur.width, 0)
    if (sumPercent > 100) {
      resultCol.value = getColWidth(resultCol.value, width)
    } else {
      resultCol.value = getColWidth(resultCol.value, width)
      setLastWidth(resultCol.value, width)
    }
  }
  if (bugCol.value.length) {
    //当宽度之和等于百分比的时候 最后一列需要处理 解决小空隙问题
    const sumPercent = bugCol.value.reduce((first: any, cur: any) => first + cur.width, 0)
    if (sumPercent > 100) {
      bugCol.value = getColWidth(bugCol.value, resultWidth)
    } else {
      bugCol.value = getColWidth(bugCol.value, resultWidth)
      setLastWidth(bugCol.value, resultWidth)
    }
  }
  if (inspectCol.value.length) {
    //当宽度之和等于百分比的时候 最后一列需要处理 解决小空隙问题
    const sumPercent = inspectCol.value.reduce((first: any, cur: any) => first + cur.width, 0)
    if (sumPercent > 100) {
      inspectCol.value = getColWidth(inspectCol.value, resultWidth)
    } else {
      inspectCol.value = getColWidth(inspectCol.value, resultWidth)
      setLastWidth(inspectCol.value, resultWidth)
    }
  }
  if (sampleCol.value.length) {
    //当宽度之和等于百分比的时候 最后一列需要处理 解决小空隙问题
    const sumPercent = sampleCol.value.reduce((first: any, cur: any) => first + cur.width, 0)
    if (sumPercent > 100) {
      sampleCol.value = getColWidth(sampleCol.value, resultWidth)
    } else {
      sampleCol.value = getColWidth(sampleCol.value, resultWidth)
      setLastWidth(sampleCol.value, resultWidth)
    }
  }
}

watchEffect(() => {
  //将当前行数据先清空再赋值
  Object.assign(formInline, {
    FSeq: '',
    FNumber: '',
    FName: '',
    FInspectResult: ''
  })
  pageInfo.value = props.tabInfo ?? {}
  const {
    currentRow,
    policyFieldInfo,
    policyInfo,
    defectFieldInfo,
    defectInfo,
    inspectFieldInfo,
    inspectInfo,
    samplingFieldInfo,
    samplingInfo
  } = pageInfo.value
  Object.assign(formInline, currentRow)
  resultCol.value = policyFieldInfo ?? []
  resultList.value = policyInfo ?? []
  bugCol.value = defectFieldInfo ?? []
  bugList.value = defectInfo ?? []
  inspectCol.value = inspectFieldInfo ?? []
  inspectList.value = inspectInfo ?? []
  sampleCol.value = samplingFieldInfo ?? []
  sampleList.value = samplingInfo ?? []
  render()
})

const refreshList = (width: number) => {
  render(width)
}
eventBus.on('refreshList', refreshList)

import type { TabsPaneContext } from 'element-plus'
import { useMessage } from '@/hooks/useMessage'
const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

const onAdd = () => {
  resultList.value.push({
    FDetailID: 0
  })
}
const message = useMessage()
const handleDelete = async (index: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    resultList.value.splice(index, 1)
  } catch {}
}
</script>
<template>
  <!-- <hr class="mt-3" /> -->
  <!-- 当前行只读信息 -->
  <el-form :inline="true" :model="formInline" class="mt-3 demo-form-inline">
    <el-form-item label="序号">
      <el-input v-model="formInline.FSeq" disabled />
    </el-form-item>
    <el-form-item label="物料编码">
      <el-input v-model="formInline.FNumber" disabled />
    </el-form-item>
    <el-form-item label="物料名称">
      <el-input v-model="formInline.FName" disabled />
    </el-form-item>
    <!-- <el-form-item label="检验结果">
      <el-select v-model="formInline.FInspectResult" placeholder="请选择" clearable>
        <el-option label="合格" value="1" />
        <el-option label="不合格" value="2" />
        <el-option label="保留" value="3" />
      </el-select>
    </el-form-item> -->
  </el-form>
  <div ref="boxRef">
    <!-- 4个Tab 检验结果 整体抽样 缺陷记录 检验项目 -->
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="检验结果" name="first"
        >使用决策&nbsp;&nbsp;&nbsp;
        <el-button type="primary" size="small" :icon="Plus" @click="onAdd"> 新增行 </el-button>
        <el-table
          class="mt-3"
          v-loading="loading"
          :data="resultList"
          stripe
          border
          style="width: 100%"
          highlight-current-row
          :header-cell-style="{ background: '#eaf6fb' }"
          @selection-change="handleSelectionChange"
        >
          <template v-for="item in resultCol" :key="item.value">
            <el-table-column
              v-if="item.isShow == 'true'"
              align="center"
              :prop="item.value"
              :label="item.label"
              :width="item.width"
              show-overflow-tooltip
            >
              <template #default="scope">
                <template v-if="item.isEdit == 'false' && isDate(item.value)">
                  <span>{{ formatDate(scope.row[item.value]) }}</span>
                </template>
                <template v-else>
                  <!-- 处理下拉框或者输入框 -->
                  <template v-if="item.isEdit == 'true'">
                    <el-select
                      v-if="item.type == 'select'"
                      v-model="scope.row[item.value]"
                      filterable
                      clearable
                      placeholder="请选择"
                      style="width: 90%"
                    >
                      <el-option
                        v-for="_ in item.cmbInfo"
                        :key="_.value"
                        :label="_.label"
                        :value="_.value"
                      />
                    </el-select>
                    <el-input
                      v-else-if="item.type == 'number'"
                      type="number"
                      v-model="scope.row[item.value]"
                      placeholder="请输入"
                      style="width: 90%"
                    />
                    <el-date-picker
                      v-else-if="item.type == 'date'"
                      type="date"
                      v-model="scope.row[item.value]"
                      placeholder="请选择"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 90%"
                    />
                    <el-input
                      v-else
                      type="text"
                      v-model="scope.row[item.value]"
                      placeholder="请输入"
                      style="width: 90%"
                    />
                  </template>
                  <template v-else>
                    <span>{{ scope.row[item.value] }}</span>
                  </template>
                </template>
              </template>
            </el-table-column>
          </template>
          <el-table-column fixed="right" label="操作" align="center" width="80">
            <template #default="scope">
              <el-button link type="danger" @click="handleDelete(scope.$index)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="缺陷记录" name="second">
        <el-table
          v-loading="loading"
          :data="bugList"
          stripe
          border
          style="width: 100%"
          highlight-current-row
          :header-cell-style="{ background: '#eaf6fb' }"
          @selection-change="handleSelectionChange"
        >
          <template v-for="item in bugCol" :key="item.value">
            <el-table-column
              v-if="item.isShow == 'true'"
              align="center"
              :prop="item.value"
              :label="item.label"
              :width="item.width"
              show-overflow-tooltip
            >
              <template #default="scope">
                <template v-if="item.isEdit == 'false' && isDate(item.value)">
                  <span>{{ formatDate(scope.row[item.value]) }}</span>
                </template>
                <template v-else>
                  <!-- 处理下拉框或者输入框 -->
                  <template v-if="item.isEdit == 'true'">
                    <el-select
                      v-if="item.type == 'select'"
                      v-model="scope.row[item.value]"
                      filterable
                      clearable
                      placeholder="请选择"
                      style="width: 90%"
                    >
                      <el-option
                        v-for="_ in item.cmbInfo"
                        :key="_.value"
                        :label="_.label"
                        :value="_.value"
                      />
                    </el-select>
                    <el-input
                      v-else-if="item.type == 'number'"
                      type="number"
                      v-model="scope.row[item.value]"
                      placeholder="请输入"
                      style="width: 90%"
                    />
                    <el-date-picker
                      v-else-if="item.type == 'date'"
                      type="date"
                      v-model="scope.row[item.value]"
                      placeholder="请选择"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 90%"
                    />
                    <el-input
                      v-else
                      type="text"
                      v-model="scope.row[item.value]"
                      placeholder="请输入"
                      style="width: 90%"
                    />
                  </template>
                  <template v-else>
                    <span>{{ scope.row[item.value] }}</span>
                  </template>
                </template>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="检验项目" name="third">
        <el-table
          v-loading="loading"
          :data="inspectList"
          stripe
          border
          style="width: 100%"
          highlight-current-row
          :header-cell-style="{ background: '#eaf6fb' }"
          @selection-change="handleSelectionChange"
        >
          <template v-for="item in inspectCol" :key="item.value">
            <el-table-column
              v-if="item.isShow == 'true'"
              align="center"
              :prop="item.value"
              :label="item.label"
              :width="item.width"
              show-overflow-tooltip
            >
              <template #default="scope">
                <template v-if="isDate(item.value)">
                  <span>{{ formatDate(scope.row[item.value]) }}</span>
                </template>
                <template v-else>
                  <span>{{ scope.row[item.value] }}</span>
                </template>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="整体抽样" name="fourth">
        <el-table
          v-loading="loading"
          :data="sampleList"
          stripe
          border
          style="width: 100%"
          highlight-current-row
          :header-cell-style="{ background: '#eaf6fb' }"
          @selection-change="handleSelectionChange"
        >
          <template v-for="item in sampleCol" :key="item.value">
            <el-table-column
              v-if="item.isShow == 'true'"
              align="center"
              :prop="item.value"
              :label="item.label"
              :width="item.width"
              show-overflow-tooltip
            >
              <template #default="scope">
                <template v-if="isDate(item.value)">
                  <span>{{ formatDate(scope.row[item.value]) }}</span>
                </template>
                <template v-else>
                  <span>{{ scope.row[item.value] }}</span>
                </template>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<style lang="less" scoped>

.demo-form-inline .el-input {
  --el-input-width: 190px;
}

.demo-form-inline .el-select {
  --el-select-width: 190px;
}
</style>
